package cn.zlj.pethome.basic.aop;

import cn.zlj.pethome.basic.annotation.LogAnno;
import cn.zlj.pethome.org.domain.Aoplog;
import cn.zlj.pethome.org.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Component
@Aspect
public class LogAop {
    @Autowired
    LogMapper logMapper;

    @Pointcut("@annotation(cn.zlj.pethome.basic.annotation.LogAnno)")
    public void pointCut(){}


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws UnknownHostException {
        // 获取到加入了注解的对应的方法
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        //获取注解
        LogAnno annotation = method.getAnnotation(LogAnno.class);
        //注解方法名字
        String method1 = annotation.method();
        //注解方法内容
        String methodDes = annotation.methodDes();
        // 执行业务方法
        System.out.println(method1+"方法执行前");
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 添加日志
        Class<?> targetCls=pjp.getTarget().getClass();
        Aoplog aoplog = new Aoplog();
        aoplog.setCzms(method1);
        aoplog.setMethod(targetCls.getPackage().getName());
        aoplog.setTime(new Date());
        InetAddress ip4 = Inet4Address.getLocalHost();
        aoplog.setIp(ip4.getHostAddress());
        logMapper.add(aoplog);
        System.out.println(method1+"方法执行后");
        //System.out.println("返回对象"+proceed);

        return proceed;
    }

}
